//
//  CMSChartsTool.swift
//  CMSCharts
//
//  Created by symbio on 2023/2/17.
//

import Foundation
import Charts

@objc public class CMSChartsTool: NSObject {
    
    
    /// 获取一条蜡烛线
    /// - Parameters:
    ///   - values: 原始点数据
    ///   - showCandleBar: true 蜡烛图 false 美国线
    ///   - increasingFilled: true 实阳线 false 空阳线
    /// - Returns: 蜡烛线
    @objc class func getCandleChartData(for values: [CandleChartDataEntry], showCandleBar: Bool, increasingFilled: Bool) -> CandleChartDataSet {
        let dataSet = CandleChartDataSet(entries: values, label: nil)
        
        //轴线方向
        dataSet.axisDependency = .left
        
        //是否在面板上直接显示数值
        dataSet.drawValuesEnabled = false
        dataSet.drawMaxMinValuesEnabled = true
        
        //true 蜡烛图 false 美国线
        dataSet.showCandleBar = showCandleBar
        
        
        //k线柱间隙
        dataSet.barSpace = 0.2
        
        //这是用于显示最高最低值区间的立线
        //dataSet.shadowColor = UIColor.black
        
        //立线的宽度
        dataSet.shadowWidth = 0.7
        dataSet.shadowColorSameAsCandle = true
        
        // close >= open 红涨
        dataSet.increasingColor = MarketSetting.red_color
        dataSet.neutralColor = MarketSetting.red_color
        // 内部是否充满颜色
        dataSet.increasingFilled = increasingFilled
        
        // open > close 绿跌
        dataSet.decreasingColor = MarketSetting.greent_color
        // 内部是否充满颜色
        dataSet.decreasingFilled = true
        
        //十字线
        dataSet.drawHorizontalHighlightIndicatorEnabled = true
        dataSet.drawVerticalHighlightIndicatorEnabled = true
        dataSet.highlightEnabled = true
        
        return dataSet
    }
    
    /// 获取一条叠加线
    /// - Parameters:
    ///   - values: 原始点数据
    ///   - showCandleBar: true 蜡烛图 false 美国线
    ///   - increasingFilled: true 实阳线 false 空阳线
    /// - Returns: 蜡烛线
    @objc class func getOverlapCandleChartData(for values: [CandleChartDataEntry], showCandleBar: Bool) -> CandleChartDataSet {
        let dataSet = CandleChartDataSet(entries: values, label: nil)
        
        //轴线方向
        dataSet.axisDependency = .right
        
        //不在面板上直接显示数值
        dataSet.drawValuesEnabled = false
        
        //true 蜡烛图 false 美国线
        dataSet.showCandleBar = showCandleBar
        
        //k线柱间隙
        dataSet.barSpace = 0.1
        
        //这是用于显示最高最低值区间的立线
        //dataSet.shadowColor = UIColor.black
        
        //立线的宽度
        dataSet.shadowWidth = 0.7
        dataSet.shadowColorSameAsCandle = true
        
        // close >= open 红涨
        dataSet.increasingColor = UIColor.blue
        dataSet.neutralColor = UIColor.blue
        // 内部是否充满颜色
        dataSet.increasingFilled = false
        
        // open > close 绿跌
        dataSet.decreasingColor = UIColor.blue
        // 内部是否充满颜色
        dataSet.decreasingFilled = true
        
        //十字线
        dataSet.drawHorizontalHighlightIndicatorEnabled = false
        dataSet.drawVerticalHighlightIndicatorEnabled = false
        dataSet.highlightEnabled = true
        
        return dataSet
    }
    
    
    /// 获取线条数据
    /// - Parameters:
    ///   - values: 点数据
    ///   - color: 线条颜色
    ///   - name: 线条名称
    /// - Returns: LineChartDataSet
    @objc class func getLineData(for values: [ChartDataEntry], color: UIColor, name: String) -> LineChartDataSet {
        //创建LineChartDataSet对象
        let picketageSet = LineChartDataSet.init(entries: values, label: name)
        
        //不在面板上直接显示数值
        picketageSet.drawValuesEnabled = false
        
        //十字线
        picketageSet.drawHorizontalHighlightIndicatorEnabled = true
        picketageSet.drawVerticalHighlightIndicatorEnabled = true
        picketageSet.highlightEnabled = true
        
        //十字线高亮颜色
        picketageSet.highlightColor = MarketSetting.highlightColor
        
        //线条颜色
        picketageSet.setColor(color)
        
        //没有圆圈
        picketageSet.circleRadius = 0.0
        picketageSet.circleHoleRadius = 0.0
        
        return picketageSet
    }
    
    /// 设置左右轴
    @objc class func setLeftRightAxis(chartView: CombinedChartView, model: CMSChartsContentModel) {
        chartView.scalingPoint = .rightCenter
        chartView.scaleYEnabled = false
        //修改背景色和边框样式
        chartView.drawBordersEnabled = true  //绘制图形区域边框
        chartView.borderColor = UIColor.blue  //边框为红色
        chartView.borderLineWidth = 0.5  //边框线条大小
        let xRange: Double = model.backAmoutCount(ofChart: model.chartType)
        //设置区域的大小（x轴上的范围）
//        chartView.setVisibleXRangeMaximum(xRange)

        switch model.chartType {
        case CMSChartsTypeTimeSharing,
             CMSChartsTypeTimeSummerUS,
             CMSChartsTypeTimeWinterUS,
             CMSChartsTypeTimeEU,
             CMSChartsTypeTimeHK:
            //禁止缩放和移动拖拽
            chartView.scaleXEnabled = false
            chartView.dragDecelerationFrictionCoef = 0.0
            //可显示范围chartView宽度能显示的数据量
            chartView.xAxis.axisMaximum = xRange
        case CMSChartsTypeFiveDay:
            //禁止缩放和移动拖拽
            chartView.scaleXEnabled = false
            chartView.dragDecelerationFrictionCoef = 0.0
        default:
            //非分时线、五日线可大小伸缩和滑动拖拽
            MarketSetting.setZoomStyleFor(Chart: chartView)
            chartView.dragEnabled = true
        }

        setLeftAxis(chartView: chartView, model: model)
        setRightAxis(chartView: chartView, model: model)
        setXAxis(chartView: chartView, model: model)
    }

    ///横轴
    @objc class func setLeftAxis(chartView: BarLineChartViewBase, model: CMSChartsContentModel) {
        //[S]设置y轴相关参数 将坐标轴显示在左边
        let leftAxis:YAxis = chartView.leftAxis
        //强制label个数
        leftAxis.forceLabelsEnabled = true
        /// 绘制网格线
        leftAxis.drawGridLinesEnabled = false
        leftAxis.drawAxisLineEnabled = false
        leftAxis.drawFirstLabelBelowAxis = true
        leftAxis.enabled = true
        leftAxis.drawGridLinesBehindDataEnabled = false
        leftAxis.onlyDisplayLabelForEvenNumber = false
        leftAxis.onlyDisplayLabelForOddNumber = false
        //label位置
        leftAxis.labelPosition = .insideChart
        //文字颜色
        leftAxis.labelTextColor = MarketSetting.labelRightTextColor
        //文字字体
        leftAxis.labelFont = MarketSetting.labelRightFont
        leftAxis.yOffset = -6
        leftAxis.xOffset = 1
        
        if !model.isAssistant {
            leftAxis.setLabelCount(5, force: true)
            switch model.chartType {
            case CMSChartsTypeTimeSharing:
                //横轴虚线
                leftAxis.gridLineDashLengths = [5.0, 5.0]
                leftAxis.onlyDisplayLabelForEvenNumber = true
                leftAxis.gridLineDashPhase = 0.0
                leftAxis.drawGridLinesEnabled = true
                leftAxis.onlyCenterGridLineDash = true
            case CMSChartsTypeFiveDay:
                //横轴虚线
                leftAxis.gridLineDashLengths = [10.0, 5.0]
                leftAxis.onlyDisplayLabelForEvenNumber = true
                leftAxis.gridLineDashPhase = 0.0
                leftAxis.drawGridLinesEnabled = true
                leftAxis.onlyCenterGridLineDash = true
            default:
                leftAxis.gridLineDashLengths = []
                leftAxis.drawGridLinesEnabled = true
                leftAxis.onlyCenterGridLineDash = false
            }
        } else {
            leftAxis.setLabelCount(2, force: true)
        }

    }
    
    
    @objc class func setRightAxis(chartView: BarLineChartViewBase, model: CMSChartsContentModel) {
        //Y轴右侧线
        let rightAxis = chartView.rightAxis
        rightAxis.drawAxisLineEnabled = false
        rightAxis.drawGridLinesEnabled = false
        rightAxis.enabled = true //开启右侧的Y轴
        rightAxis.labelPosition = .insideChart
        rightAxis.yOffset = -6
        rightAxis.xOffset = 1
        rightAxis.drawFirstLabelBelowAxis = true
        
        if model.isAssistant { //去除副图网格横线
            rightAxis.drawLabelsEnabled = false
        } else {
            if model.chartType != CMSChartsTypeTimeSharing
                && model.chartType != CMSChartsTypeFiveDay {
                rightAxis.drawLabelsEnabled = false
            } else {
                rightAxis.setLabelCount(2, force: true)
                rightAxis.drawLabelsEnabled = true
            }
        }
    }
    
    
    @objc class func setXAxis(chartView: BarLineChartViewBase, model: CMSChartsContentModel) {
        let xAxis = chartView.xAxis
        xAxis.enabled = true
        xAxis.drawGridLinesEnabled = false
        xAxis.drawLabelsEnabled = false
        xAxis.labelPosition = .bottom
        //第一个和最后一个图会显示一半(显示不全)
        xAxis.spaceMin = 0.5
        xAxis.spaceMax = 0.5
        //将轴标签居中，label在两竖线之间显示，默认false的情况下label中心为竖线
        xAxis.centerAxisLabelsEnabled = true
        //为true，图表将避免图表中的第一个和最后一个标签条目从图表的边缘“剪辑”
        xAxis.avoidFirstLastClippingEnabled = true
        //自定义限制线绘制在数据前面
        xAxis.drawLimitLinesBehindDataEnabled = true
        xAxis.removeAllLimitLines()

        switch model.chartType {
        case CMSChartsTypeTimeSharing,
             CMSChartsTypeTimeWinterUS,
             CMSChartsTypeTimeSummerUS,
             CMSChartsTypeTimeEU,
             CMSChartsTypeTimeHK:

            let labelFont: UIFont = NSUIFont.systemFont(ofSize: 9)
            let labelLineHeight = labelFont.lineHeight
            drawLimitLinesForType(xAxis: xAxis, model: model, isAssistant: model.isAssistant, labelFont: labelFont)
            break
        case CMSChartsTypeFiveDay:
            if !model.isAssistant {
                xAxis.drawGridLinesEnabled = true
                xAxis.drawLabelsEnabled = true
            }
            xAxis.setLabelCount(6, force: true)
        case CMSChartsTypeCandleStick:
            if model.isAssistant && model.chartData.lineData != nil {
                xAxis.drawLabelsEnabled = true
                xAxis.centerAxisLabelsEnabled = false
                xAxis.setLabelCount(2, force: true)
            }
        default:
            break
        }
    }
    
    /// 根据配置画限制线及label
    private class func drawLimitLinesForType(xAxis: XAxis, model: CMSChartsContentModel, isAssistant: Bool, labelFont: UIFont) {
        //画竖线
        let modelArray: Array<CMSChartsXPositionModel> = model.backXPositionInfo(for: model.chartType)
        modelArray.forEach { item in
            let limitLine: ChartLimitLine = ChartLimitLine(limit: item.xPosition, label: (isAssistant && item.isShowLabel) ?  item.name : "")
            limitLine.lineWidth = item.isShowLine ? xAxis.axisLineWidth : 0
            limitLine.lineColor = xAxis.axisLineColor
            limitLine.lineDashLengths = xAxis.axisLineDashLengths
            limitLine.lineDashPhase = xAxis.axisLineDashPhase
            limitLine.labelPosition = .bottomOutside
            limitLine.valueFont = labelFont
            limitLine.valueTextColor = xAxis.axisLineColor
            limitLine.labelAlignment = item.labelAlignment
            xAxis.addLimitLine(limitLine)
        }
    }
    
    /// 显示竞价
    @objc class public var showBidding: Bool {
        get {
            UserDefaults.standard.value(forKey: "CMSChartsShowBiddingKey") as? Bool ?? false
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "CMSChartsShowBiddingKey")
        }
    }
    

    
}

